﻿import objc
from AppKit import NSColor, NSCalibratedRGBColorSpace

class NSColor(objc.Category(NSColor)):

    def complement(self):
        this = self.asRGB()
        red = 1.0 - this.redComponent()
        green = 1.0 - this.greenComponent()
        blue = 1.0 - this.blueComponent()
        alpha = this.alphaComponent()
        return NSColor.colorWithCalibratedRed_green_blue_alpha_(red, green, blue, alpha)
        
    def asRGB(self):
        if self.colorSpaceName() == NSCalibratedRGBColorSpace: 
            return self
        else:
            return self.colorUsingColorSpaceName_(NSCalibratedRGBColorSpace)
            
    def asSvg(self):
        return self.asString()[:-2] # ignore alpha
            
    def asString(self):
        this = self.asRGB()
        red = int(this.redComponent() * 255)
        green = int(this.greenComponent() * 255)
        blue = int(this.blueComponent() * 255)
        alpha = int(this.alphaComponent() * 255)
        return '#%02X%02X%02X%02X' % (red, green, blue, alpha)
        
    @classmethod
    def colorFromString_(self, string):
        string = string[1:] # trim off leading hash
        red = int(string[0:2], 16) / 255.0
        green = int(string[2:4], 16) / 255.0
        blue = int(string[4:6], 16) / 255.0
        alpha = int(string[6:8], 16) / 255.0
        return NSColor.colorWithCalibratedRed_green_blue_alpha_(red, green, blue, alpha)
        


